﻿using System;
using System.ComponentModel;

namespace NSDuctTape
{
	internal sealed class PropertyChangeHandler : IDisposable
	{
		public PropertyChangeHandler(object target, IntPtr instance)
		{
			_target = target;
			_instance = instance;

			(_target as INotifyPropertyChanged).PropertyChanged += new PropertyChangedEventHandler(TargetPropertyChanged);
			(_target as INotifyPropertyChanging).PropertyChanging += new PropertyChangingEventHandler(TargetPropertyChanging);
		}

		public void Dispose()
		{
			if (!_disposed)
			{
				(_target as INotifyPropertyChanged).PropertyChanged -= new PropertyChangedEventHandler(TargetPropertyChanged);
				(_target as INotifyPropertyChanging).PropertyChanging -= new PropertyChangingEventHandler(TargetPropertyChanging);
				_disposed = true;
			}
		}

		private void TargetPropertyChanging(object sender, PropertyChangingEventArgs e)
		{
			// TODO: We actually allow keys to be different from their property names, so sending the PropertyName that we got
			// is not really the safest thing to do.
			ObjectiveCMethods.SendMessage(_instance, Selectors.WillChangeValueForKey, NativeString.StringToNativeString(e.PropertyName));
		}

		private void TargetPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			ObjectiveCMethods.SendMessage(_instance, Selectors.DidChangeValueForKey, NativeString.StringToNativeString(e.PropertyName));
		}

		readonly object _target;
		readonly IntPtr _instance;
		bool _disposed;
	}
}
